/**
 * 医院站点管理 API
 */

import { api } from '../api'

export interface HospitalSite {
  siteId: string;
  name: string;
  address: string;
  coordinates: {
    longitude: number;
    latitude: number;
  };
  zoom?: number;
  district?: string;
  city?: string;
  province?: string;
  status: 'active' | 'inactive' | 'maintenance';
  description?: string;
  contactInfo?: {
    phone?: string;
    email?: string;
    website?: string;
  };
  facilities?: string[];
  operatingHours?: {
    weekdays?: string;
    weekends?: string;
    holidays?: string;
  };
  capacity?: {
    beds?: number;
    departments?: number;
    doctors?: number;
  };
  createdAt?: string;
  updatedAt?: string;
}

export interface EquipmentUsage {
  usageId: string;
  siteId: string;
  equipmentId: string;
  equipmentName: string;
  equipmentType: 'bed' | 'ct' | 'mri' | 'xray' | 'ultrasound' | 'wheelchair' | 'defibrillator' | 'ventilator' | 'other';
  usageRate: number;
  totalCapacity: number;
  currentUsage: number;
  status: 'normal' | 'warning' | 'critical' | 'offline';
  department?: string;
  floor?: string;
  room?: string;
  lastUpdated?: string;
  createdAt?: string;
}

class HospitalAPI {
  
  /**
   * 获取所有医院站点
   */
  async getSites(params?: {
    status?: string;
    city?: string;
    province?: string;
    page?: number;
    limit?: number;
  }) {
    try {
      const response = await api.get('/hospital-site', params || {})
      return response
    } catch (error) {
      console.error('获取医院站点失败:', error)
      throw error
    }
  }

  /**
   * 根据坐标获取附近的医院站点
   */
  async getNearbySites(params: {
    longitude: number;
    latitude: number;
    maxDistance?: number;
    limit?: number;
  }) {
    try {
      const response = await api.get('/hospital-site/nearby', params)
      return response
    } catch (error) {
      console.error('获取附近医院站点失败:', error)
      throw error
    }
  }

  /**
   * 获取医院站点详情
   */
  async getSiteDetail(siteId: string) {
    try {
      const response = await api.get(`/hospital-site/${siteId}`)
      return response
    } catch (error) {
      console.error('获取医院站点详情失败:', error)
      throw error
    }
  }

  /**
   * 创建医院站点
   */
  async createSite(siteData: Omit<HospitalSite, 'siteId' | 'createdAt' | 'updatedAt'>) {
    try {
      const response = await api.post('/hospital-site', siteData)
      return response
    } catch (error) {
      console.error('创建医院站点失败:', error)
      throw error
    }
  }

  /**
   * 更新医院站点
   */
  async updateSite(siteId: string, siteData: Partial<HospitalSite>) {
    try {
      const response = await api.put(`/hospital-site/${siteId}`, siteData)
      return response
    } catch (error) {
      console.error('更新医院站点失败:', error)
      throw error
    }
  }

  /**
   * 删除医院站点
   */
  async deleteSite(siteId: string) {
    try {
      const response = await api.delete(`/hospital-site/${siteId}`)
      return response
    } catch (error) {
      console.error('删除医院站点失败:', error)
      throw error
    }
  }

  /**
   * 获取医院站点设备使用率
   */
  async getSiteEquipment(siteId: string) {
    try {
      const response = await api.get(`/hospital-site/${siteId}/equipment`)
      return response
    } catch (error) {
      console.error('获取设备使用率失败:', error)
      throw error
    }
  }

  /**
   * 更新设备使用率数据
   */
  async updateEquipmentUsage(siteId: string, equipmentData: Partial<EquipmentUsage> | Partial<EquipmentUsage>[]) {
    try {
      const response = await api.post(`/hospital-site/${siteId}/equipment`, equipmentData)
      return response
    } catch (error) {
      console.error('更新设备使用率失败:', error)
      throw error
    }
  }

  /**
   * 批量获取多个站点的基本信息
   */
  async getBatchSites(siteIds: string[]) {
    try {
      const promises = siteIds.map(id => this.getSiteDetail(id))
      const responses = await Promise.allSettled(promises)
      
      const sites: HospitalSite[] = []
      responses.forEach((response, index) => {
        if (response.status === 'fulfilled' && response.value?.success) {
          sites.push(response.value.data)
        } else {
          console.warn(`获取站点 ${siteIds[index]} 失败:`, response)
        }
      })
      
      return {
        success: true,
        data: sites
      }
    } catch (error) {
      console.error('批量获取站点失败:', error)
      throw error
    }
  }

  /**
   * 搜索医院站点
   */
  async searchSites(keyword: string, params?: {
    city?: string;
    province?: string;
    limit?: number;
  }) {
    try {
      // 通过名称搜索
      const allSites = await this.getSites({
        ...params,
        limit: params?.limit || 50
      })
      
      if (!allSites?.success || !allSites?.data?.sites) {
        return { success: true, data: [] }
      }
      
      // 前端过滤（后端也可以实现搜索功能）
      const filteredSites = allSites.data.sites.filter((site: HospitalSite) =>
        site.name.toLowerCase().includes(keyword.toLowerCase()) ||
        site.address?.toLowerCase().includes(keyword.toLowerCase()) ||
        site.district?.toLowerCase().includes(keyword.toLowerCase())
      )
      
      return {
        success: true,
        data: filteredSites
      }
    } catch (error) {
      console.error('搜索医院站点失败:', error)
      throw error
    }
  }
}

// 创建实例
const hospitalAPI = new HospitalAPI()

export { hospitalAPI }
export default hospitalAPI